package com.cl.web;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cl.service.ExcelService;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cl.auth.LoginVo;
import com.cl.auth.RefreshVo;
import com.cl.dto.ResultDTO;
import com.cl.dto.UserDTO;
import com.cl.entity.AccessToken;
import com.cl.service.CommonService;
import com.cl.service.FileService;

@Controller
public class WebController {

	 @Autowired
	 private FileService fileService;
	 
	 @Autowired
	 private CommonService commonService;

	 @Autowired
	 private ExcelService excelService;
	 
	 @Value("#{applicationProperties['shiro.logoutUrl']}")
	 protected String LOGOUT_URL;

	//文件下载
	@RequiresPermissions("*:view")
	@RequestMapping(value = "/fileopen", method = RequestMethod.GET)	
	public void openfile( @RequestParam(value = "fp", required = true) String fp,
		HttpServletRequest request, HttpServletResponse response) throws IOException{
		fileService.onOpenFile(fp,request, response);
	}
	
	// 处理文件上传
	@RequiresPermissions("*:create")
	@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
	public void fileUpload(@RequestParam MultipartFile[] files, HttpServletRequest request,HttpServletResponse response)
			throws IllegalStateException, IOException {
		fileService.onFileUpload(files,request, response);
	}
	
	@RequestMapping(value = "/cc")
	public String login(Model model, HttpServletRequest request) {
		return "redirect:/dc/web/";
	}	
	 @SuppressWarnings("rawtypes")
	 @RequestMapping(value = "/cc/listUsers", method = RequestMethod.GET)
	 @ResponseBody
	 public ResultDTO listUsers(
			 @RequestParam(value = "limit", required = false) int limit,
			 @RequestParam(value = "kw", required = false) String kw,
			 @RequestParam(value = "filter", required = false) String filter) throws ClassNotFoundException {	
		 return commonService.listEntities("com.cl.entity.UUser", "name", kw, limit,filter,null);
	 }
	
	@RequestMapping(value = "/cc/authenticate", method = RequestMethod.POST)
	@ResponseBody
	public UserDTO authenticate(@RequestBody LoginVo request) {		 
		return commonService.login(request);
	}
		
	@RequestMapping(value = "/cc/logout", method = RequestMethod.GET)
	@ResponseBody
	public String logout(@RequestParam(value = "token", required = true) String token) {
		commonService.logout(token);
		if (token != null && token.indexOf("ST") >= 0) {
			return LOGOUT_URL;
		} else {
			return "/dc/web/";
		}
	}
	
    @RequestMapping(value = "/refresh", method = RequestMethod.POST)
    public AccessToken refresh(@RequestBody RefreshVo refreshVo) {
        return commonService.refresh(refreshVo);
    }

	@RequestMapping(value = "/cc/error")
	public String error(Model model) {
		return "redirect:/dc/web/";
	}
		
	@RequiresPermissions("*:create")
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public void importExcel(@RequestParam MultipartFile files, HttpServletRequest request,HttpServletResponse response)
			throws IllegalStateException, IOException {
		//fileService.onFileUpload(files,request, response);
		response.setContentType("text/html; charset=UTF-8");
		//设置响应给前台内容的PrintWriter对象
		PrintWriter out = response.getWriter();
		if(files.isEmpty() ){
			out.println("文件为空");
			return;
		}
		String originalFilename = files.getOriginalFilename();
		if(!originalFilename.endsWith("xls") && !originalFilename.endsWith("xlsx")){
			out.println("只支持excel格式的文件");
			return;
		}
		/*out.println("excel");
		out.println(originalFilename);*/
		
		fileService.importExcel(files, request, response);
		
		out.close();
	}

	/**
	 *
	 * @param filter
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequiresPermissions("*:view")
	@RequestMapping(value = "/api/WLOutExcel")
	public void wlOutExcel(
			@RequestParam(value = "filter", required = false) String filter,
			HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		OutputStream out = response.getOutputStream();
		response.reset(); //清空输出流
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = dateFormatter.format(new Date()) + ".xls";
		response.setHeader("Content-disposition","attachment;filename=" + fileName);
		excelService.WLOutExcel(out, filter);
		out.flush();
		out.close();
	}

}